package cn.com.libertymutual.core.common.json.databind.annotation;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;

import com.fasterxml.jackson.databind.ObjectMapper;

public class SpringJsonFilterAdvice {
	
	public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
		
			MethodSignature msig = (MethodSignature) pjp.getSignature();
	
	        SpringJsonFilter annotation = msig.getMethod().getAnnotation( SpringJsonFilter.class );
	
	        SpringJsonFilters annotations = msig.getMethod().getAnnotation( SpringJsonFilters.class );
	
	        if (annotation == null && annotations == null) {  
					return pjp.proceed();
	        }
	
	        ObjectMapper mapper = new ObjectMapper();
	        mapper.setSerializationInclusion(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL);
	        if (annotation != null) {
	            Class<?> mixin = annotation.mixin();
	            Class<?> target = annotation.target();
	            //MixInResolver
	            
	            if (target != null) {
	                ///mapper.getSerializationConfig().addMixInAnnotations(target, mixin);
	            	mapper.addMixIn(target, mixin);
	            } else {
	                ///mapper.getSerializationConfig().addMixInAnnotations(msig.getMethod().getReturnType(), mixin);
	            	mapper.addMixIn(msig.getMethod().getReturnType(), mixin);
	            }  
	        }  
	
	        if (annotations != null) {
	            SpringJsonFilter[] filters= annotations.value();
	
	            for(SpringJsonFilter filter :filters){  
	
	                Class<?> mixin = filter.mixin();
	                Class<?> target = filter.target();
	
	                if (target != null) {
	                	///mapper.getSerializationConfig().addMixInAnnotations(target, mixin);  
	                	mapper.addMixIn(target, mixin);
	                } else {
	                    ///mapper.getSerializationConfig().addMixInAnnotations(msig.getMethod().getReturnType(), mixin);
	                	mapper.addMixIn(msig.getMethod().getReturnType(), mixin);
	                }
	            }
	
	        }
	    
	        mapper.writeValue(WebContext.getInstance().getResponse().getOutputStream(), pjp.proceed());
        return null;
    }  
}
